package com.lt.lumentracks.entity.dto.common;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.util.StringUtils;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class PageDTO {

    private static final Long DEFAULT_PAGE_NUM = 1L;
    private static final Long DEFAULT_PAGE_SIZE = 10L;


    /**
     * 当前页码，默认第1页
     */
    @NotNull(message = "页码不能为空")
    @Min(value = 1L, message = "页码不能小于1")
    private Long page = DEFAULT_PAGE_NUM;
    
    /**
     * 每页显示数量，默认10条
     */
    @NotNull(message = "每页查询数量不能为空")
    @Min(value = 1L, message = "每页查询数量不能小于1")
    private Long size = DEFAULT_PAGE_SIZE;
    
    /**
     * 排序字段
     */
    private String sortBy;
    
    /**
     * 是否升序，true-升序，false-降序
     */
    private Boolean isAsc = true;


    
    public PageDTO(Long page, Long size) {
        this.page = page;
        this.size = size;
    }



    /**
     * 获取偏移量，用于数据库分页查询
     */
    public Long getOffset() {
        if (page == null || size == null) {
            return 0L;
        }
        return (page - 1) * size;
    }


    /**
     * 转换为 MyBatis-Plus 的 Page 对象
     */
    public <T> Page<T> toMpPage() {
        Page<T> mpPage = new Page<>(page, size);
        
        // 设置排序
        if (StringUtils.hasText(sortBy)) {
            OrderItem ot = new OrderItem();
            ot.setColumn(sortBy);
            ot.setAsc(isAsc);
            mpPage.addOrder(new OrderItem());
        }
        return mpPage;
    }

}